package com.huazai.juc.cec.thread.past;

public class SynchronizedThread {
    static int counter = 0;
    // static修饰的，则元素是属于类本身的，不属于对象，与类一起加载一次，只有一个
    static final Object room = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i ++) {
                synchronized (room) {
                    counter ++;
                }
            }
        }, "t1");

        Thread t2 = new Thread(() -> {
            for (int i = 0;i < 5000; i ++) {
                synchronized (room) {
                    counter --;
                }
            }
        }, "t2");

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(counter);
    }

    public synchronized void test0() {
        System.out.println("locked");
    }
    /**
     * _____________________
     * 如果方法是实例方法的话，同步方法默认用this作为所得对象
     * 上下的两个方法等价的
     * _____________________
     */
    public void test1() {
        synchronized (SynchronizedThread.class) {
            System.out.println("locked");
        }
    }


    /**
     * 如果是静态方法的话，同步方法默认用类名.class作为的锁对象
     */
    public synchronized static void test2() {
        System.out.println("locked");
    }
    //等价于
    public void test3() {
        synchronized(SynchronizedThread.class) {
            System.out.println("locked");
        }
    }

}
